package org.fastsyncer.web.controller.login;

import org.fastsyncer.common.entity.RestResult;
import org.fastsyncer.web.interceptor.Ticket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证处理
 *
 * @author AE86
 * @ClassName: LoginController
 * @Description: 登录验证，注销
 * @date: 2017年7月7日 上午10:03:33
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Ticket ticket;

    @RequestMapping("")
    public String index(ModelMap model) {
        return "login/login.html";
    }

    @PostMapping(value = "/login")
    @ResponseBody
    public RestResult login(HttpServletRequest request, @RequestParam(value = "username") String username,
                            @RequestParam(value = "userpwd") String userpwd) {
        try {
            // 生成认证票据,如果验证失败，抛出异常
            ticket.createTicket(request, username, userpwd);
            logger.info("login success!");
            return RestResult.restSuccess("login success!");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return RestResult.restFail("对不起,您输入的帐号或密码错误");
    }

    @GetMapping(value = "/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            ticket.removeTicket(request.getSession());
            response.sendRedirect(ticket.getLoginUrl());
            logger.info("logout success!");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

}
